import time

# 导入异步
import asyncio


def sync_demo():

    def task_exec(task_name, delay):
        print(f"任务{task_name}来了,开始执行")
        time.sleep(delay)  # 阻塞
        print(f"任务{task_name}完成")

    start = time.time()

    task_exec("job1", 2)
    task_exec("job2", 1)
    end = time.time()
    print("总共耗时=", f"{(end - start):.2f}")


async def async_exec_task(task, delay):
    print(f"任务:{task}来了")
    await asyncio.sleep(delay)  # 非阻塞等待
    print(f"任务:{task}执行完毕")


def generator_task():

    while True:
        i = yield
        print("i=====", i)
        if i is None:
            i = 0
        yield async_exec_task(f"job{i}", i)


gen = generator_task()

gen.send(None)


async def async_demo():

    # 使用列表推导式生成任务列表
    task_queue = [async_exec_task(f"job{i}", i) for i in range(5)]
    # task_queue = [gen.send(i + 1) for i in range(5)]

    start = time.time()

    await asyncio.gather(*task_queue)
    # await asyncio.gather(gen.send(100))

    end = time.time()

    print(f"总共耗时:{(end-start):.2f}")


# 运行对比
# print("=== 同步版本 ===")
# sync_demo()  # 耗时约3秒

print("\n=== 异步版本 ===")
asyncio.run(async_demo())  # 耗时约5秒
